package be.jprojects.tests.filter;

import java.util.ArrayList;

import javax.swing.AbstractListModel;

public class FilterModel extends AbstractListModel {

	private ArrayList<Object> items, filterItems;
	private FilteredJList source;

	public FilterModel(FilteredJList source) {
		super();
		this.source = source;
		items = new ArrayList<Object>();
		filterItems = new ArrayList<Object>();
	}

	public Object getElementAt(int index) {
		if (index < filterItems.size())
			return filterItems.get(index);
		else
			return null;
	}

	public int getSize() {
		return filterItems.size();
	}

	public void addItem(Object item) {
		items.add(item);
		refilter();
	}

	public void refilter() {
		filterItems.clear();
		String term = source.getFilterField().getText();
		source.clearSelection();

		for (int i = 0; i < items.size(); i++)
			if (items.get(i).toString().toLowerCase().indexOf(term.toLowerCase(), 0) != -1)
				filterItems.add(items.get(i));
		fireContentsChanged(this, 0, getSize());
		source.getFilterLabel().setText(getSize() + " items");
	}

	public void clearItems() {
		items.clear();
		filterItems.clear();
		fireContentsChanged(this, 0, getSize());
	}
	

}
